home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11505 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  71 lines

  1. Path: prodigy.com!usenet
  2. From: Victor Muslin <vmuslin@prodigy.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Templates Question
  5. Date: Thu, 14 Mar 1996 16:35:26 -0500
  6. Organization: Prodigy Services Company
  7. Message-ID: <3148911E.1E02@prodigy.com>
  8. NNTP-Posting-Host: 192.203.241.84
  9. Mime-Version: 1.0
  10. Content-Type: text/plain; charset=us-ascii
  11. Content-Transfer-Encoding: 7bit
  12. X-Mailer: Mozilla 2.0GoldB1 (WinNT; I)
  13.  
  14. I want to define a class, let's call it "River", whose interface
  15. is similar to an IOStream. That is, I would like to be able to do:
  16.  
  17. main()
  18. {
  19.     River r;
  20.     int i = 10;
  21.  
  22.     r << i << "foo";
  23. }
  24.  
  25. My first impulse was to do:
  26.  
  27. class River
  28. {
  29.    public:
  30.     River& operator<<(int);
  31.     River& operator<<(char*);
  32.    ...
  33. };
  34.  
  35. However, redefining operator << for every built in data type
  36. is not fun and I would like to avoid long complex macros.
  37.  
  38. So I thought that templates would be perfect:
  39.  
  40. template <class T>
  41. class River<T>
  42. {
  43.     public:
  44.     River<T>&    operator<<(T);
  45.    ...
  46. };
  47.  
  48. The problem with this seems to be that when I instansiate a
  49. River object:
  50.  
  51.     River<int> r;
  52.  
  53. the template generates only:
  54.  
  55.     River& operator<<(int);
  56.  
  57. function, which means that I can do:
  58.  
  59.     r << i;
  60.  
  61. but not
  62.  
  63.     r << "foo";
  64.  
  65. Is this correct and if so, any suggestions on how to avoid
  66. using macros or redefining << by hand for every data type?
  67.  
  68. Please send a copy of replies to vmuslin@prodigy.com.
  69.  
  70. Thanks.
  71.